<template>
  <div class="settings-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>系统设置</h2>
        <p>管理系统配置和参数</p>
      </div>
    </div>
    
    <el-row :gutter="24">
      <!-- 基本设置 -->
      <el-col :xs="24" :lg="12">
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span>基本设置</span>
            </div>
          </template>
          
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicFormRules"
            label-width="120px"
          >
            <el-form-item label="站点名称" prop="siteName">
              <el-input v-model="basicForm.siteName" placeholder="请输入站点名称" />
            </el-form-item>
            
            <el-form-item label="最大连接数" prop="maxConnections">
              <el-input-number
                v-model="basicForm.maxConnections"
                :min="1"
                :max="10000"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="默认超时(秒)" prop="defaultTimeout">
              <el-input-number
                v-model="basicForm.defaultTimeout"
                :min="1"
                :max="300"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="日志保留天数" prop="logRetentionDays">
              <el-input-number
                v-model="basicForm.logRetentionDays"
                :min="1"
                :max="365"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                :loading="basicLoading"
                @click="saveBasicSettings"
              >
                保存基本设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 功能开关 -->
      <el-col :xs="24" :lg="12">
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <el-icon><Switch /></el-icon>
              <span>功能开关</span>
            </div>
          </template>
          
          <div class="switch-group">
            <div class="switch-item">
              <div class="switch-info">
                <div class="switch-title">访问日志</div>
                <div class="switch-desc">启用后将记录所有代理访问日志</div>
              </div>
              <el-switch
                v-model="featuresForm.enableAccessLog"
                @change="saveFeaturesSettings"
              />
            </div>
            
            <div class="switch-item">
              <div class="switch-info">
                <div class="switch-title">速率限制</div>
                <div class="switch-desc">启用后将对客户端请求进行速率限制</div>
              </div>
              <el-switch
                v-model="featuresForm.enableRateLimit"
                @change="onRateLimitChange"
              />
            </div>
          </div>
          
          <!-- 速率限制配置 -->
          <el-form
            v-if="featuresForm.enableRateLimit"
            ref="rateLimitFormRef"
            :model="featuresForm.rateLimit"
            label-width="120px"
            class="rate-limit-form"
          >
            <el-divider>速率限制配置</el-divider>
            
            <el-form-item label="请求数限制">
              <el-input-number
                v-model="featuresForm.rateLimit.requests"
                :min="1"
                :max="10000"
                style="width: 100%"
              />
              <div class="form-tip">每个时间窗口内允许的最大请求数</div>
            </el-form-item>
            
            <el-form-item label="时间窗口(秒)">
              <el-input-number
                v-model="featuresForm.rateLimit.window"
                :min="1"
                :max="3600"
                style="width: 100%"
              />
              <div class="form-tip">速率限制的时间窗口长度</div>
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                :loading="featuresLoading"
                @click="saveFeaturesSettings"
              >
                保存功能设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 安全设置 -->
    <el-row :gutter="24" style="margin-top: 24px">
      <el-col :xs="24" :lg="12">
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <el-icon><Lock /></el-icon>
              <span>修改密码</span>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordFormRules"
            label-width="120px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                :loading="passwordLoading"
                @click="changePassword"
              >
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 系统信息 -->
      <el-col :xs="24" :lg="12">
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <el-icon><Monitor /></el-icon>
              <span>系统信息</span>
            </div>
          </template>
          
          <el-descriptions :column="1" border>
            <el-descriptions-item label="系统版本">
              v1.0.0
            </el-descriptions-item>
            <el-descriptions-item label="运行时间">
              {{ uptime }}
            </el-descriptions-item>
            <el-descriptions-item label="内存使用">
              <el-progress
                :percentage="memoryUsage"
                :stroke-width="8"
                :text-inside="true"
                :color="getProgressColor(memoryUsage)"
              />
            </el-descriptions-item>
            <el-descriptions-item label="CPU使用率">
              <el-progress
                :percentage="cpuUsage"
                :stroke-width="8"
                :text-inside="true"
                :color="getProgressColor(cpuUsage)"
              />
            </el-descriptions-item>
            <el-descriptions-item label="磁盘使用">
              <el-progress
                :percentage="diskUsage"
                :stroke-width="8"
                :text-inside="true"
                :color="getProgressColor(diskUsage)"
              />
            </el-descriptions-item>
            <el-descriptions-item label="最后更新">
              {{ formatDateTime(lastUpdateTime) }}
            </el-descriptions-item>
          </el-descriptions>
          
          <div class="system-actions">
            <el-button @click="refreshSystemInfo">
              <el-icon><Refresh /></el-icon>
              刷新信息
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  Setting,
  Switch,
  Lock,
  Monitor,
  Refresh
} from '@element-plus/icons-vue'
import { settingsApi } from '../api'
import { useUserStore } from '../stores/user.ts'
import { formatDateTime } from '../utils'
import type { SystemSettings, ChangePasswordForm } from '../types'

const userStore = useUserStore()

// 响应式数据
const basicLoading = ref(false)
const featuresLoading = ref(false)
const passwordLoading = ref(false)
const basicFormRef = ref<FormInstance>()
const rateLimitFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 系统信息
const uptime = ref('7天 3小时 25分钟')
const memoryUsage = ref(65)
const cpuUsage = ref(42)
const diskUsage = ref(78)
const lastUpdateTime = ref(new Date().toISOString())

let systemInfoTimer: NodeJS.Timeout | null = null

// 基本设置表单
const basicForm = reactive({
  siteName: '',
  maxConnections: 1000,
  defaultTimeout: 30,
  logRetentionDays: 30
})

// 功能设置表单
const featuresForm = reactive({
  enableAccessLog: true,
  enableRateLimit: false,
  rateLimit: {
    requests: 100,
    window: 60
  }
})

// 密码修改表单
const passwordForm = reactive<ChangePasswordForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const basicFormRules: FormRules = {
  siteName: [
    { required: true, message: '请输入站点名称', trigger: 'blur' }
  ],
  maxConnections: [
    { required: true, message: '请输入最大连接数', trigger: 'blur' }
  ],
  defaultTimeout: [
    { required: true, message: '请输入默认超时时间', trigger: 'blur' }
  ],
  logRetentionDays: [
    { required: true, message: '请输入日志保留天数', trigger: 'blur' }
  ]
}

const passwordFormRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const loadSettings = async () => {
  try {
    const response = await settingsApi.getSettings()
    
    if (response.code === 200) {
      const settings = response.data
      
      // 更新基本设置
      basicForm.siteName = settings.siteName
      basicForm.maxConnections = settings.maxConnections
      basicForm.defaultTimeout = Math.floor(settings.defaultTimeout / 1000) // 转换为秒
      basicForm.logRetentionDays = settings.logRetentionDays
      
      // 更新功能设置
      featuresForm.enableAccessLog = settings.enableAccessLog
      featuresForm.enableRateLimit = settings.enableRateLimit
      featuresForm.rateLimit = { ...settings.rateLimit }
    }
  } catch (error) {
    console.error('Failed to load settings:', error)
    ElMessage.error('加载设置失败')
  }
}

const saveBasicSettings = async () => {
  if (!basicFormRef.value) return
  
  try {
    const valid = await basicFormRef.value.validate()
    if (!valid) return
    
    basicLoading.value = true
    
    const settings: Partial<SystemSettings> = {
      siteName: basicForm.siteName,
      maxConnections: basicForm.maxConnections,
      defaultTimeout: basicForm.defaultTimeout * 1000, // 转换为毫秒
      logRetentionDays: basicForm.logRetentionDays
    }
    
    const response = await settingsApi.updateSettings(settings)
    
    if (response.code === 200) {
      ElMessage.success('基本设置保存成功')
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('Failed to save basic settings:', error)
    ElMessage.error('保存基本设置失败')
  } finally {
    basicLoading.value = false
  }
}

const saveFeaturesSettings = async () => {
  try {
    featuresLoading.value = true
    
    const settings: Partial<SystemSettings> = {
      enableAccessLog: featuresForm.enableAccessLog,
      enableRateLimit: featuresForm.enableRateLimit,
      rateLimit: { ...featuresForm.rateLimit }
    }
    
    const response = await settingsApi.updateSettings(settings)
    
    if (response.code === 200) {
      ElMessage.success('功能设置保存成功')
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('Failed to save features settings:', error)
    ElMessage.error('保存功能设置失败')
  } finally {
    featuresLoading.value = false
  }
}

const onRateLimitChange = (enabled: boolean) => {
  if (enabled) {
    // 如果启用速率限制，保存设置
    saveFeaturesSettings()
  } else {
    // 如果禁用速率限制，直接保存
    saveFeaturesSettings()
  }
}

const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    passwordLoading.value = true
    
    const result = await userStore.changePassword(
      passwordForm.oldPassword,
      passwordForm.newPassword,
      passwordForm.confirmPassword
    )
    
    if (result.success) {
      ElMessage.success(result.message)
      resetPasswordForm()
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('Failed to change password:', error)
    ElMessage.error('修改密码失败')
  } finally {
    passwordLoading.value = false
  }
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

const refreshSystemInfo = () => {
  // 模拟刷新系统信息
  memoryUsage.value = Math.floor(Math.random() * 40) + 40 // 40-80%
  cpuUsage.value = Math.floor(Math.random() * 50) + 20 // 20-70%
  diskUsage.value = Math.floor(Math.random() * 30) + 60 // 60-90%
  lastUpdateTime.value = new Date().toISOString()
  
  ElMessage.success('系统信息已刷新')
}

const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

const startSystemMonitoring = () => {
  systemInfoTimer = setInterval(() => {
    // 模拟系统监控数据更新
    memoryUsage.value = Math.max(20, Math.min(90, memoryUsage.value + (Math.random() - 0.5) * 10))
    cpuUsage.value = Math.max(10, Math.min(95, cpuUsage.value + (Math.random() - 0.5) * 20))
    
    // 更新运行时间
    const startTime = new Date().getTime() - (7 * 24 * 60 + 3 * 60 + 25) * 60 * 1000
    const now = new Date().getTime()
    const diff = now - startTime
    
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
    const minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000))
    
    uptime.value = `${days}天 ${hours}小时 ${minutes}分钟`
  }, 5000)
}

const stopSystemMonitoring = () => {
  if (systemInfoTimer) {
    clearInterval(systemInfoTimer)
    systemInfoTimer = null
  }
}

// 生命周期
onMounted(() => {
  loadSettings()
  startSystemMonitoring()
})

onUnmounted(() => {
  stopSystemMonitoring()
})
</script>

<style scoped>
.settings-page {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title h2 {
  margin: 0 0 4px 0;
  font-size: 24px;
  color: #2c3e50;
}

.page-title p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.setting-card {
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.switch-group {
  margin-bottom: 20px;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.switch-item:last-child {
  border-bottom: none;
}

.switch-info {
  flex: 1;
}

.switch-title {
  font-weight: 500;
  margin-bottom: 4px;
  color: #2c3e50;
}

.switch-desc {
  font-size: 12px;
  color: #7f8c8d;
  line-height: 1.4;
}

.rate-limit-form {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.system-actions {
  margin-top: 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .switch-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .switch-item .el-switch {
    align-self: flex-end;
  }
}
</style>